package myServer.processor;

import myServer.session.ServerSession;
import myServer.session.SessionMap;
import org.springframework.stereotype.Service;
import protobuf.protoClass.ProtoMsg;

import java.util.List;

@Service("ChatRedirectProcessor")
public class ChatTransmitProcessor implements ServerProcessor {

    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.MESSAGE_REQUEST;
    }

    @Override
    public boolean perform(ServerSession session, ProtoMsg.Message protoMessage) {

        //获取 聊天信息
        ProtoMsg.MessageRequest messageRequest = protoMessage.getMessageRequest();
        System.out.println("chatMsg from= "
                + messageRequest.getFrom()
                + " , to= " + messageRequest.getTo()
                + " , content= " + messageRequest.getContent());
        //获取 信息接收方
        String to = messageRequest.getTo();
        //获取 信息接收方所有的在线登录终端
        List<ServerSession> sessionsByUserID = SessionMap.instance().getServerSessionsByUserID(to);
        if (sessionsByUserID == null) {
            //离线状态
            System.out.println("[" + to + "] 不在线，发送失败！");
        } else {
            sessionsByUserID.forEach((session1 -> {
                //向 信息接收方所有在线终端发送信息，保证信息多平台同步
                session1.writeAndFlush(protoMessage);
            }));
        }
        return false;
    }

}
